﻿// 技术文档： https://ai-cyber-security.feishu.cn/docx/OtD2dK0lHotM86xRX5XcziTtnTb

using PeriodicalTaskDemo.Tasks;
using System;
using System.Windows.Forms;

namespace PeriodicalTaskDemo
{
    public partial class MainForm : Form
    {
        static int messageid = 1000;

        PeriodicalTaskDemo.Tasks.PeriodicalTask pt = new Tasks.PeriodicalTask(1000);

        public MainForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (btnRun.Text == "Start")
            {
                pt.Start();
                btnRun.Text = "Stop";
                ckTaskPaused.Enabled = true;
                ckTaskPaused.Checked = false;
            }
            else
            {
                pt.Stop();
                btnRun.Text = "Start";
                ckTaskPaused.Enabled = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            pt.Stop();
        }

        private void ckTaskPaused_CheckedChanged(object sender, EventArgs e)
        {
            if (ckTaskPaused.Checked)
            {
                pt.Pause();
            }
            else
            {
                pt.Resume();
            }
        }

        public void AddLog(string msg)
        {
            listBox1.Items.Insert(0, $"{messageid++} {DateTime.Now:yyyy/MM/dd HH:mm:ss.fff} {msg}");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // Start task
            pt.BeforeStart += () => AddLog("Started.");

            // running
            pt.Processing += () =>
            {
                AddLog("Working...");
                while (listBox1.Items.Count > 20)
                {
                    listBox1.Items.RemoveAt(20);
                    XLogger.Info("The 20th item is removed.");
                }
            };

            // stop task
            pt.AfterStop += () => AddLog("Stopped.");

            numericUpDown1.Value = pt.Interval;
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            pt.Interval = (int)numericUpDown1.Value;
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDown1.Value = 3000;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDown1.Value = 100;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDown1.Value = 1000;
        }
    }
}
